import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:popup_menu/popup_menu.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:tencent_cloud_chat_sdk/enum/conversation_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_status.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:video_ducafecat_flutter_v3/common/index.dart';

import 'index.dart';
import 'widgets/index.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _ChatViewGetX();
  }
}

class _ChatViewGetX extends GetView<ChatController> {
  _ChatViewGetX({Key? key}) : super(key: key);

  /// 用户的 uid 作为唯一标识
  final String uniqueTag = Get.arguments?["uid"]!;

  /// 聊天类型 1: 单聊 2: 群聊
  final type = int.tryParse(Get.arguments['type'].toString());

  // override tag
  @override
  String? get tag => uniqueTag;

  // 创建菜单
  PopupMenu cratePopMenu(context,
      {bool? isSelf, Function(MenuItemProvider)? onClickMenu}) {
    PopupMenu menu = PopupMenu(
      context: context,
      config: MenuConfig(
        backgroundColor: AppColors.primary,
        itemHeight: 55,
      ),
      items: [
        MenuItem(
            title: LocaleKeys.commonBottomRemove.tr,
            userInfo: "delete",
            textStyle: TextStyle(fontSize: 10.0, color: AppColors.onPrimary),
            image: Icon(
              Icons.delete,
              color: AppColors.onPrimary,
              size: 24,
            )),
        if (isSelf == true)
          MenuItem(
              title: LocaleKeys.commonBottomUndo.tr,
              userInfo: "undo",
              textStyle: TextStyle(fontSize: 10.0, color: AppColors.onPrimary),
              image: Icon(
                Icons.undo,
                color: AppColors.onPrimary,
                size: 24,
              )),
      ],
      onClickMenu: onClickMenu,
      // onDismiss: onDismiss,
    );
    return menu;
  }

  // 视频加工行
  Widget _buildVideoCompressItem() {
    return <Widget>[
      // 视频压缩
      MsgVideoCompressWidget(
        initAsset: controller.waitSendAssetVideo,
        onCompleted: controller.onVideoCompress, // 视频压缩完成
      ).width(160).paddingRight(5),

      // 头像
      AvatarWidget(
          "${Constants.imageServer}/avatar/${UserService.to.profile.avatar}"),
    ].toRow(
      mainAxisAlignment: MainAxisAlignment.end,
    );
  }

  // 消息行
  Widget _buildMsgItem(
    BuildContext context,
    V2TimMessage message, {
    bool isSelf = false,
  }) {
    // 消息id ，自己刚创建时为空
    String? msgID = message.msgID;

    // 消息项 key
    final elemKey =
        msgID == null ? GlobalKey() : controller.getMessageListKey(msgID);

    // 聊天消息 文字、表情、图片、语音、视频
    List<Widget> ws = [];

    // 头像
    ws.add(message.faceUrl == null
        ? InitialsWidget(message.sender!)
        : AvatarWidget(message.faceUrl!));

    // 间隔
    ws.add(SizedBox(width: AppSpace.iconTextSmail));

    // 文字、表情、图片、语音、视频
    Widget? msgElem;
    switch (message.elemType) {
      // 本地自定义消息
      case MessageElemType.V2TIM_ELEM_TYPE_CUSTOM:
        msgElem = MsgCustomElemWidget(
          key: elemKey,
          message: message,
          membersList: controller.membersList,
        );
        break;
      // 群系统消息
      case MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS:
        msgElem = MsgGroupTipsElemWidget(
          key: elemKey,
          message: message,
          membersList: controller.membersList,
        );
        break;
      // 文字消息
      case MessageElemType.V2TIM_ELEM_TYPE_TEXT:
        msgElem = MsgTextElemWidget(
          key: elemKey,
          isSelf: isSelf,
          message: message,
        );
        break;
      // 表情消息
      case MessageElemType.V2TIM_ELEM_TYPE_FACE:
        msgElem = MsgFaceElemWidget(
          key: elemKey,
          message: message,
        );
        break;
      // 语音消息
      case MessageElemType.V2TIM_ELEM_TYPE_SOUND:
        msgElem = MsgSoundElemWidget(
          key: elemKey,
          message: message,
          isSelf: isSelf,
          isPlaying: controller.isSoundPlaying(message.msgID),
          onPlaySoundStateChange: controller.onMessageListRefresh,
        );
        break;
      // 图片消息
      case MessageElemType.V2TIM_ELEM_TYPE_IMAGE:
        msgElem = MsgImageElemWidget(
          key: elemKey,
          message: message,
        );
        break;
      // 视频消息
      case MessageElemType.V2TIM_ELEM_TYPE_VIDEO:
        msgElem = MsgVideoElemWidget(
          key: elemKey,
          message: message,
          controller: controller,
          onStateChange: controller.onMessageStateChange,
        );
        break;
    }

    if (msgElem != null) {
      // 事件
      msgElem = msgElem.gestures(
        // 发送失败，双击重发
        onDoubleTap: message.status == MessageStatus.V2TIM_MSG_STATUS_SEND_FAIL
            ? () => controller.onReSend(message)
            : null,

        // 长按菜单
        onLongPress: () {
          var menu = cratePopMenu(
            context,
            isSelf: isSelf,
            onClickMenu: (item) {
              if (item.menuUserInfo == "delete") {
                controller.onDeleteLocalMsg(message);
              } else if (item.menuUserInfo == "undo") {
                controller.onUndoMsg(message);
              }
            },
          );
          menu.show(widgetKey: elemKey);
        },
      );

      // 错误消息, 红色背景边框
      if (message.status == MessageStatus.V2TIM_MSG_STATUS_SEND_FAIL) {
        msgElem = msgElem.paddingAll(5).decorated(
              color: AppColors.errorContainer,
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: AppColors.error, width: 1),
            );
      }

      // 加入
      ws.add(msgElem);

      // 撑开行
      ws.add(const SizedBox.shrink().expanded());
    }

    // 聊天左右布局
    if (isSelf) {
      ws = ws.reversed.toList();
    }

    return ws
        .toRow(
          crossAxisAlignment: CrossAxisAlignment.start,
        )
        .paddingBottom(AppSpace.listRow);
  }

  // 消息列表
  Widget _buildMsgList() {
    return GetBuilder<ChatController>(
        id: "messageList",
        tag: tag,
        builder: (_) {
          var messageList = controller.messageList;
          // messageList 按 timestamp 时间戳 倒序
          messageList.sort((left, right) {
            final rightTimestamp = right.timestamp ?? 0;
            final leftTimestamp = left.timestamp ?? 0;
            return rightTimestamp.compareTo(leftTimestamp);
          });

          return SmartRefresher(
            controller: controller.refreshController,
            enablePullUp: true,
            enablePullDown: false,
            onLoading: controller.onLoading,
            footer: const ClassicFooter(
              loadingIcon: SizedBox(
                width: 25.0,
                height: 25.0,
                child: CupertinoActivityIndicator(),
              ),
            ),
            child: CustomScrollView(
              reverse: true,
              controller: controller.scrollController,
              slivers: [
                // 视频加工行
                if (controller.waitSendAssetVideo != null)
                  _buildVideoCompressItem().sliverBox,

                // 消息列表
                SliverList.builder(
                  itemCount: messageList.length,
                  itemBuilder: (context, index) {
                    V2TimMessage msg = messageList[index];
                    return _buildMsgItem(context, msg, isSelf: msg.isSelf!);
                  },
                ),
              ],
            ),
          );
        });
  }

  // 主视图
  Widget _buildView() {
    return _buildMsgList()
        .paddingAll(AppSpace.listView)
        .onTap(controller.onCloseChatBar);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChatController>(
      // 初始控制器
      init: ChatController(
        receiver: uniqueTag, // tag
        type: type ?? ConversationType.V2TIM_C2C, // 类型
      ),
      id: "chat",
      tag: tag,
      builder: (_) {
        return Scaffold(
          // 全局key
          key: controller.scaffoldKey,

          // 顶部导航栏
          appBar: AppBar(
            title: Text(controller.title),
            actions: [
              if (controller.isGroup)
                IconButton(
                  icon: const Icon(Icons.more_horiz_outlined),
                  onPressed: controller.onGroupSettingOpen,
                ),
            ],
          ),

          // 背景色
          backgroundColor: AppColors.surfaceVariant,

          // 正文
          body: SafeArea(
            child: _buildView(),
          ),

          // 底部聊天栏
          bottomNavigationBar: ChatBarWidget(
            key: controller.chatBarKey,
            onTextSend: controller.onTextSend,
            onFaceSend: controller.onFaceSend,
            onSoundSend: controller.onSoundSend,
            onImageSend: controller.onImageSend,
            onVideoSend: controller.onVideoSend,
          ),

          // 右侧弹出 Drawer
          endDrawer: controller.isGroup
              ? Drawer(
                  child: SafeArea(
                      child: ChatGroupSettingWidget(uniqueTag: uniqueTag)),
                )
              : null,
        );
      },
    );
  }
}
